<template>
    <div class="medical-safety-container">
        <global-search @submitSearch="submitSearch" class="global-tool-search"/>
        <div class="page-height-box">
            <view-card :cardData="cardData"/>
            <div class="echart-table-box">
                <el-row :gutter="10">
                    <el-col :span="12">
                        <div class="content">
                            <p class="title">高/低倍率病案趋势分析</p>
                            <data-chart :chartData="highLowEchart"/>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="content">
                            <p class="title">费用占比分析</p>
                            <data-chart :chartData="expenseEchart"/>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="content">
                            <p class="title">DRG盈亏趋势分析</p>
                            <data-chart :chartData="DRGEchart"/>
                        </div>
                    </el-col>
                    <el-col :span="12">
                        <div class="content">
                            <p class="title">平均住院费用趋势分析</p>
                            <data-chart :chartData="avgFeeEchart"/>
                        </div>
                    </el-col>
                    <el-col :span="24">
                        <div class="content">
                            <div class="title-tool-btn">
                                <p class="title">汇总列表</p>
                                <el-button type="text" class="export-btn" v-auth="{code: 200004004001}" @click="toExport">
                                    <svg-icon icon-class="export"/>
                                    导出
                                </el-button>
                            </div>
                            <el-table
                                border
                                :data="tableData"
                                tooltip-effect="light"
                                style="width: 100%"
                                :empty-text="emptyText"
                                @selection-change="handleSelectionChange">
                                <el-table-column
                                    show-overflow-tooltip
                                    type="selection"
                                    align="center"
                                    width="30"
                                    fixed>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="date"
                                    type="index"
                                    align="center"
                                    label="序号"
                                    width="40"
                                    fixed>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="department"
                                    align="left"
                                    label="科室名称"
                                    min-width="100"
                                    fixed>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="resident"
                                    align="center"
                                    v-if="isShowDoctor"
                                    label="住院医生"
                                    min-width="90">
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="drgCase"
                                    align="center"
                                    sortable
                                    label="入组病案数"
                                    min-width="90">
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="totalFee"
                                    align="center"
                                    sortable
                                    label="住院总费用"
                                    min-width="100">
                                    <template slot-scope="scope">
                                        {{scope.row.totalFee | getMoneyNum}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="avgFee"
                                    align="right"
                                    sortable
                                    label="平均住院费用"
                                    min-width="110">
                                    <template slot-scope="scope">
                                        {{scope.row.avgFee | getMoneyNum}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="drgIncome"
                                    align="right"
                                    sortable
                                    label="DRG盈亏"
                                    min-width="100">
                                    <template slot-scope="scope">
                                        {{scope.row.drgIncome | getMoneyNum}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="low"
                                    align="center"
                                    sortable
                                    label="低倍率病案"
                                    min-width="100">
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="high"
                                    align="center"
                                    sortable
                                    label="高倍率病案"
                                    min-width="100">
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="drug"
                                    align="center"
                                    sortable
                                    label="药品占比"
                                    min-width="80">
                                    <template slot-scope="scope">
                                        {{scope.row.drug | toPercentage}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="inspection"
                                    align="center"
                                    sortable
                                    label="检查占比"
                                    min-width="80">
                                    <template slot-scope="scope">
                                        {{scope.row.inspection | toPercentage}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="surgery"
                                    align="center"
                                    sortable
                                    label="手术占比"
                                    min-width="80">
                                    <template slot-scope="scope">
                                        {{scope.row.surgery | toPercentage}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="material"
                                    align="center"
                                    sortable
                                    label="耗材占比"
                                    min-width="80">
                                    <template slot-scope="scope">
                                        {{scope.row.material | toPercentage}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="test"
                                    align="center"
                                    sortable
                                    label="检验占比"
                                    min-width="80">
                                    <template slot-scope="scope">
                                        {{scope.row.test | toPercentage}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    prop="other"
                                    align="center"
                                    sortable
                                    label="其他占比"
                                    min-width="80">
                                    <template slot-scope="scope">
                                        {{scope.row.other | toPercentage}}
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    show-overflow-tooltip
                                    label="操作"
                                    align="center"
                                    min-width="50"
                                    fixed="right">
                                    <template slot-scope="scope">
                                        <el-button type="text" @click="toPageInfo(scope.row)">明细</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>
    </div>
</template>

<script>
    import {
        expensesOverview,
        expensesTrend,
        expensesCosts,
        expensesSummary,
        exportExpensesSummary
    } from '@/api/data-analysis/expenses-info'
    import {toPercentage, getMoneyNum} from '@/utils/filters'
    import DataChart from '@/components/DataChart'
    import ViewCard from '@/components/ViewCard'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'Dashboard',
        data () {
            return {
                // 是否显示住院医生
                isShowDoctor: false,
                // 图表数据
                highLowEchart: {
                    xAxis: [],
                    series: [{
                        name: '低倍率病案',
                        data: []
                    }, {
                        name: '高倍率病案',
                        data: []
                    }],
                    rate: [],
                    yAxisName: ['(人)'],
                    id: 'highLowEchart'
                },
                // 费用分析
                expenseEchart: {
                    type: 'pie',
                    series: [],
                    id: 'expenseEchart'
                },
                // 图表数据
                DRGEchart: {
                    xAxis: [],
                    series: [{
                        name: 'DRG盈亏',
                        data: []
                    }],
                    yAxisName: ['(元)'],
                    id: 'DRGEchart'
                },
                // 图表数据
                avgFeeEchart: {
                    xAxis: [],
                    series: [{
                        name: '平均住院费用',
                        data: []
                    }],
                    yAxisName: ['(元)'],
                    id: 'avgFeeEchart'
                },
                // 卡片数据
                cardData: [
                    {
                        title: 'DRG入组病案数',
                        data: 0,
                        scale: '0%',
                        tips: '已入组的病案数',
                        pageName: 'ExpensesListIndex'
                    }, {
                        title: '住院总费用',
                        data: 0,
                        tips: '入组病案住院总费用之和',
                        pageName: 'ExpensesListIndex'
                    }, {
                        title: '平均住院费用',
                        data: 0,
                        tips: '入组病例住院总费用之和/病案数',
                        pageName: 'ExpensesListIndex'
                    }, {
                        title: 'DRG盈亏',
                        data: 0,
                        tips: 'DRG组标准费用-住院费用总费用',
                        pageName: 'ExpensesListIndex'
                    }, {
                        title: '低倍率病案数',
                        data: 0,
                        scale: '0%',
                        tips: '实际费用与标准费用对比(低于设定值即为低倍率病案)',
                        pageName: 'ExpensesListIndex',
                        query: {
                            rate: 1
                        }
                    }, {
                        title: '高倍率病案数',
                        data: 0,
                        scale: '0%',
                        tips: '实际费用与标准费用对比(高于设定值即为高倍率病案)',
                        pageName: 'ExpensesListIndex',
                        query: {
                            rate: 2
                        }
                    }
                ],
                // 表格数据
                tableData: [],
                // 选中的数据
                multipleSelection: [],
                // 空数据时显示的文本内容
                emptyText: '暂无数据',
                // 使用储存的数据，不去请求
                useStoreOverview: false,
                useStoreTrend: false,
                useStoreCosts: false,
                useStoreSummary: false,
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStoreOverview = this.$route.query.tags === 'tags'
            this.useStoreTrend = this.$route.query.tags === 'tags'
            this.useStoreCosts = this.$route.query.tags === 'tags'
            this.useStoreSummary = this.$route.query.tags === 'tags'
        },
        mounted () {
        },
        methods: {
            /**
             * 提交查询
             * @param form 筛选条件
             */
            submitSearch (form) {
                this.isShowDoctor = form.department !== ''
                this.getExpensesOverview(form)
                this.getExpensesTrend(form)
                this.getExpensesCosts(form)
                this.getExpensesSummary(form)
            },
            /**
             * 费用总览查询
             * @param params 查询参数
             */
            getExpensesOverview (params) {
                if (this.getSession(this.$route.name, 'expensesOverview') && this.useStoreOverview) {
                    this.useStoreOverview = false
                    let res = this.getSession(this.$route.name, 'expensesOverview')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.cardData[0].data = res.data.drgCase
                        this.cardData[0].scale = res.data.groupRate
                        this.cardData[1].data = getMoneyNum(res.data.totalFee)
                        this.cardData[2].data = getMoneyNum(res.data.avgFee)
                        this.cardData[3].data = getMoneyNum(res.data.drgIncome)
                        this.cardData[4].data = res.data.lowNum
                        this.cardData[4].scale = res.data.lowRate
                        this.cardData[5].data = res.data.highNum
                        this.cardData[5].scale = res.data.highRate
                    }
                } else {
                    expensesOverview(params).then(res => {
                        this.useStoreOverview = false
                        this.setSession(this.$route.name, {expensesOverview: res})
                        if (res.code.toString() === '200') {
                            this.cardData[0].data = res.data.drgCase
                            this.cardData[0].scale = res.data.groupRate
                            this.cardData[1].data = getMoneyNum(res.data.totalFee)
                            this.cardData[2].data = getMoneyNum(res.data.avgFee)
                            this.cardData[3].data = getMoneyNum(res.data.drgIncome)
                            this.cardData[4].data = res.data.lowNum
                            this.cardData[4].scale = res.data.lowRate
                            this.cardData[5].data = res.data.highNum
                            this.cardData[5].scale = res.data.highRate
                        }
                    })
                }
            },
            /**
             * 趋势查询
             * @param params 查询参数
             */
            getExpensesTrend (params) {
                if (this.getSession(this.$route.name, 'expensesTrend') && this.useStoreTrend) {
                    this.useStoreTrend = false
                    let res = this.getSession(this.$route.name, 'expensesTrend')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.highLowEchart = {
                            xAxis: res.data.month,
                            series: [{
                                name: '低倍率病案',
                                data: res.data.lowNum
                            }, {
                                name: '高倍率病案',
                                data: res.data.highNum
                            }],
                            rate: [{
                                name: '低倍率病案',
                                data: res.data.lowRate
                            }, {
                                name: '高倍率病案',
                                data: res.data.highRate
                            }],
                            yAxisName: ['(人)'],
                            id: 'highLowEchart'
                        }
                        this.DRGEchart = {
                            xAxis: res.data.month,
                            series: [{
                                name: 'DRG盈亏',
                                data: res.data.drgIncome
                            }],
                            yAxisName: ['(元)'],
                            id: 'DRGEchart'
                        }
                        this.avgFeeEchart = {
                            xAxis: res.data.month,
                            series: [{
                                name: '平均住院费用',
                                data: res.data.avgFee
                            }],
                            yAxisName: ['(元)'],
                            id: 'avgFeeEchart'
                        }
                    }
                } else {
                    expensesTrend(params).then(res => {
                        this.useStoreTrend = false
                        this.setSession(this.$route.name, {expensesTrend: res})
                        if (res.code.toString() === '200') {
                            this.highLowEchart = {
                                xAxis: res.data.month,
                                series: [{
                                    name: '低倍率病案',
                                    data: res.data.lowNum
                                }, {
                                    name: '高倍率病案',
                                    data: res.data.highNum
                                }],
                                rate: [{
                                    name: '低倍率病案',
                                    data: res.data.lowRate
                                }, {
                                    name: '高倍率病案',
                                    data: res.data.highRate
                                }],
                                yAxisName: ['(人)'],
                                id: 'highLowEchart'
                            }
                            this.DRGEchart = {
                                xAxis: res.data.month,
                                series: [{
                                    name: 'DRG盈亏',
                                    data: res.data.drgIncome
                                }],
                                yAxisName: ['(元)'],
                                id: 'DRGEchart'
                            }
                            this.avgFeeEchart = {
                                xAxis: res.data.month,
                                series: [{
                                    name: '平均住院费用',
                                    data: res.data.avgFee
                                }],
                                yAxisName: ['(元)'],
                                id: 'avgFeeEchart'
                            }
                        }
                    })
                }
            },
            /**
             * 费用占比查询
             * @param params 查询参数
             */
            getExpensesCosts (params) {
                if (this.getSession(this.$route.name, 'expensesCosts') && this.useStoreCosts) {
                    this.useStoreCosts = false
                    let res = this.getSession(this.$route.name, 'expensesCosts')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.expenseEchart = {
                            type: 'pie',
                            series: [
                                {value: res.data.drug, name: '药品占比'},
                                {value: res.data.material, name: '耗材占比'},
                                {value: res.data.test, name: '检验占比'},
                                {value: res.data.surgery, name: '手术占比'},
                                {value: res.data.inspection, name: '检查占比'},
                                {value: res.data.other, name: '其他'}
                            ],
                            id: 'expenseEchart'
                        }
                    }
                } else {
                    expensesCosts(params).then(res => {
                        this.useStoreCosts = false
                        this.setSession(this.$route.name, {expensesCosts: res})
                        if (res.code.toString() === '200') {
                            this.expenseEchart = {
                                type: 'pie',
                                series: [
                                    {value: res.data.drug, name: '药品占比'},
                                    {value: res.data.material, name: '耗材占比'},
                                    {value: res.data.test, name: '检验占比'},
                                    {value: res.data.surgery, name: '手术占比'},
                                    {value: res.data.inspection, name: '检查占比'},
                                    {value: res.data.other, name: '其他'}
                                ],
                                id: 'expenseEchart'
                            }
                        }
                    })
                }
            },
            /**
             * 汇总列表查询
             * @param params 查询参数
             */
            getExpensesSummary (params) {
                this.emptyText = '加载中...'
                if (this.getSession(this.$route.name, 'expensesSummary') && this.useStoreSummary) {
                    this.useStoreSummary = false
                    let res = this.getSession(this.$route.name, 'expensesSummary')
                    this.emptyText = '暂无数据'
                    if (res.code.toString() === '200') {
                        this.tableData = res.data
                        this.tableData.forEach((item, index) => {
                            this.tableData[index] = {
                                ...item,
                                index
                            }
                        })
                    }
                } else {
                    expensesSummary(params).then(res => {
                        this.useStoreSummary = false
                        this.setSession(this.$route.name, {expensesSummary: res})
                        this.emptyText = '暂无数据'
                        if (res.code.toString() === '200') {
                            this.tableData = res.data
                            this.tableData.forEach((item, index) => {
                                this.tableData[index] = {
                                    ...item,
                                    index
                                }
                            })
                        }
                    }).catch(() => {
                        this.emptyText = '暂无数据'
                    })
                }
            },
            /**
             * 设置右侧显示文字
             * @param percentage 当前进度
             */
            progressFormat (percentage) {
                return Math.round(percentage * this.total / 100) + '例'
            },
            /**
             * 表格数据选中
             */
            handleSelectionChange (val) {
                this.multipleSelection = val
            },
            /**
             * 获取选中id
             */
            getSelectId () {
                let arr = []
                if (this.multipleSelection.length) {
                    this.multipleSelection.forEach(item => {
                        arr.push(item.index)
                    })
                    return arr
                } else {
                    return false
                }
            },
            /**
             * 导出汇总列表
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                params.indexList = this.getSelectId() || []
                this.$store.dispatch('app/UpdateLoadingText', '0%')
                this.$store.dispatch('app/UpdateIsExport', true)
                this.$store.dispatch('app/UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                exportExpensesSummary(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('app/UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('费用情况汇总列表', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('app/UpdateIsExport', false)
                        this.$store.dispatch('app/UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                let arr = [{
                    header: '序号', key: 'index', width: 10
                }, {
                    header: '科室名称', key: 'department', width: 16
                }, {
                    header: '住院医生', key: 'resident', width: 16
                }, {
                    header: '入组病案数', key: 'drgCase', width: 16
                }, {
                    header: '住院总费用', key: 'totalFee', width: 24
                }, {
                    header: '平均住院费用', key: 'avgFee', width: 24
                }, {
                    header: 'DRG盈亏', key: 'drgIncome', width: 24
                }, {
                    header: '低倍率病案', key: 'low', width: 16
                }, {
                    header: '高倍率病案', key: 'high', width: 16
                }, {
                    header: '药品占比', key: 'drug', width: 12
                }, {
                    header: '检查占比', key: 'inspection', width: 12
                }, {
                    header: '手术占比', key: 'surgery', width: 12
                }, {
                    header: '耗材占比', key: 'material', width: 12
                }, {
                    header: '检验占比', key: 'test', width: 12
                }, {
                    header: '其他占比', key: 'other', width: 12
                }]
                if (!this.isShowDoctor) {
                    arr.splice(2, 1)
                }
                return arr
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    data[i].totalFee = getMoneyNum(data[i].totalFee)
                    data[i].avgFee = getMoneyNum(data[i].avgFee)
                    data[i].drgIncome = getMoneyNum(data[i].drgIncome)
                    data[i].drug = toPercentage(data[i].drug)
                    data[i].inspection = toPercentage(data[i].inspection)
                    data[i].surgery = toPercentage(data[i].surgery)
                    data[i].material = toPercentage(data[i].material)
                    data[i].test = toPercentage(data[i].test)
                    data[i].other = toPercentage(data[i].other)
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('app/UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('app/UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('app/UpdateLoadingText', '100%')
                    this.$store.dispatch('app/UpdateIsExport', false)
                    this.$store.dispatch('app/UpdateLoading', false)
                })
            },
            /**
             * 查看数据详情
             * @param row 行数据
             */
            toPageInfo (row) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                this.setGetStore('ExpensesListIndex', {...query, department: row.dep, depName: row.department, resident: this.isShowDoctor ? row.resident : ''})
                this.$router.push({name: 'ExpensesListIndex', query: {department: row.dep, depName: row.department}})
            }
        },
        filters: {
            toPercentage,
            getMoneyNum
        },
        components: {
            ViewCard,
            DataChart
        }
    }
</script>

<style scoped lang="scss">
    .medical-safety-container {
        .echart-table-box {
            .el-col {
                &:nth-child(5) {
                    margin-bottom: 0;
                    height: auto;
                }
            }
        }
    }
</style>
